<template>
  <view class="container gray_bg create_repair">
    <tm-form @submit="confirm" ref="formRef" v-model="form" transprent :label-width="180" :margin="[0, 0]" :border="false">
      <view class="form_title">填写报修信息</view>
      <tm-sheet :margin="[16, 20]" :round="3" :shadow="2">
        <tm-form-item label="报修类型" field="repair_type">
          <view @click="repairVisible =!repairVisible" class="flex flex-row flex-row-center-end">
            <tm-text :userInteractionEnabled="false" :label="form.repair_type_text || '请选择报修类型'"></tm-text>
            <tm-icon :userInteractionEnabled="false" :font-size="24" name="tmicon-angle-right"></tm-icon>
          </view>
          <tm-picker
              @confirm="selectRepair"
              :columns="repairTypes"
              map-key="name"
              v-model:model-str="show.repairStr"
              v-model:show="repairVisible"
              :default-value="show.repairIndex"
              v-model="show.repairIndex"
          ></tm-picker>
        </tm-form-item>
        <tm-form-item label="报修地址" field="repair_adress">
<!--           修改报修地址带出相关数据 todo-->
          <view @click="addressVisible = !addressVisible" class="flex flex-row flex-row-center-end">
            <tm-text :userInteractionEnabled="false" :label="form.repair_adress || '请选择报修地址'"></tm-text>
            <tm-icon :userInteractionEnabled="false" :font-size="24" name="tmicon-angle-right"></tm-icon>
          </view>
          <tm-picker
              @confirm="selectRepairAddress"
              :columns="repairAddress"
              map-key="number"
              v-model:model-str="show.addressStr"
              v-model:show="addressVisible"
              :default-value="show.addressIndex"
              v-model="show.addressIndex"
          ></tm-picker>
        </tm-form-item>
        <tm-form-item label="详细地址" field="address" :padding="[0, 0]">
          <tm-input :inputPadding="[0, 0]" v-model.lazy="form.address" :transprent="true" :showBottomBotder="false"> </tm-input>
        </tm-form-item>
        <tm-form-item label="报修租客" field="merchant_name" :padding="[0, 0]">
          <view class="form_static_label">
            <view @click="industryVisible = !industryVisible" class="flex flex-row flex-row-center-end">
              <tm-text :userInteractionEnabled="false" :label="form.merchant_name"></tm-text>
            </view>
          </view>
        </tm-form-item>
        <tm-form-item label="报修人" field="">
          <view @click="industryVisible = !industryVisible" class="flex flex-row flex-row-center-end">
            <tm-text :userInteractionEnabled="false" :label="userInfo.real_name || '请选择报修人'"></tm-text>
            <tm-icon :userInteractionEnabled="false" :font-size="24" name="tmicon-angle-right"></tm-icon>
          </view>
        </tm-form-item>
        <tm-form-item required label="上门时间" field="order_start_date" :padding="[0, 0]" :rules="[{ required: true, message: '请选择上门时间' }]">
          <view @click="selectServiceTime" class="flex flex-row flex-row-center-end">
            <tm-text :userInteractionEnabled="false" :label="repariDate.rTime || '请选择上门时间'"></tm-text>
            <tm-icon :userInteractionEnabled="false" :font-size="24" name="tmicon-angle-right"></tm-icon>
          </view>
          <view class="form_static_label" @click="selectServiceTime"></view>
        </tm-form-item>
        <tm-form-item label="选择故障描述类型" field="" :padding="[0, 0]" parentClass="item_block">
            <view class="tag_list">
              <tm-tag v-for="(item, i) in tagList" :outlined="!item.checked" :round="25" :shadow="0" color="#165DFF" size="m" :label="item.name" :key="item.id" @click="() => selectTag(item, i)"></tm-tag>
            </view>
          <tm-input
              :inputPadding="[12]"
              placeholder="请填写故障描述（选填）"
              confirm-hold
              confirm-type="换行"
              :border="1"
              v-model.lazy="form.description"
              autoHeight
              type="textarea"
          ></tm-input>
        </tm-form-item>
        <view class="upload_file">
          <view v-for="(item, i) in fileList" class="upload_img" :key="i">
            <view class="img_inner">
              <tm-image preview :src="item.url"></tm-image>
              <view class="upload_delete" @click="() => deletePic(i)">
                <tm-icon fontSize="32" name="iconfont icon-tupianshanchu" color="#FF0000"></tm-icon>
              </view>
            </view>
          </view>

<!--                        :fileList="fileList"-->
          <view class="upload_section">
            <u-upload
                :fileList="fileList"
                @afterRead="afterRead"
                @delete="deletePic"
                name="1"
                accept="media"
                :maxCount="4"
                :previewImage="false"
                :previewFullImage="false"
            >
              <view class="upload_file_btn">
                +
              </view>
            </u-upload>
          </view>
        </view>

      </tm-sheet>

      <view class="form_title">我的信息</view>
      <view class="my_info">
        <tm-sheet :margin="[16, 20]" :round="3" :shadow="2">
          <view class="cus_item">
            <view class="cus_item_label">租客名称</view>
            <view class="cus_item_value">{{userInfo.merchant_name}}</view>
          </view>
          <view class="cus_item">
            <view class="cus_item_label">姓名</view>
            <view class="cus_item_value">{{userInfo.real_name}}</view>
          </view>
          <view class="cus_item">
            <view class="cus_item_label">手机号码</view>
            <view class="cus_item_value">{{userInfo.phone}}</view>
          </view>
        </tm-sheet>
      </view>

      <view class="cus_footer_btn">
        <tm-button block form-type="submit" label="提交报修" round="25"></tm-button>
      </view>
    </tm-form>
<!--     选择时间弹框  -->
    <uni-popup ref="popupRef" type="bottom">
      <view class="popup_header">
        <view class="popup_header_title">
          上门时间
        </view>
        <view class="popup_close" @click="closePopup">×</view>
      </view>
      <view class="popup-content">
        <view class="date_section">
          <view v-for="(item, i) in repairDates" :key="i" :class="['date_item', item.isShowTime ? 'selected' : '']" @click="() => selectDate(item, i)">
            <view class="time_week">{{item.week}}</view>
            <view class="time_date">{{item.date}}</view>
<!--            时间点  -->
            <view v-if="item.isShowTime" class="time_section">
              <view v-for="(time, index) in item.time_list" class="select_time">
                <view v-if="time.is_expire" class="time_item disabled">{{time.title}}</view>
<!--                <view v-if="time.is_expire" :class="[time.is_expire ? 'disabled' : '' , '']">{{time.title}}</view>-->
                <view v-else :class="['time_item', time.isChecked ? 'selected': '']" @click="() => selectTime(i, index)">{{time.title}}</view>
              </view>
            </view>

          </view>
        </view>
      </view>
      <view class="popup_footer">
        <view class="popup_footer_inner">
          <tm-button block label="确认" round="25" @click="handleSelect"></tm-button>
        </view>
      </view>
    </uni-popup>

<!--     加载弹框 -->
    <u-toast ref="uToastRef"></u-toast>
  </view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import {each} from 'lodash'
import moment from 'moment'
import { onLoad } from '@dcloudio/uni-app';
import {storeToRefs} from "pinia";
import { useInfoStore } from '@/store/userInfo'
import { getAllRepairType, createOrder, getOrderDetail, updateOrder, getHouseList, getRepairTime } from '@/api_request/api'
import utils from '@/utils/index'
import { ASSETS_HOST } from '@/config'
import { upLoadFile, uniUpload } from '@/utils/utils'

const userStore = useInfoStore()
const { userInfo } : any = storeToRefs(userStore)
console.log('jp======userInfo',userInfo)
const merchant_id = ref(userInfo.value.merchant_id) || 12
const community_id = ref(userInfo.value.community_id) || 1

const uToastRef = ref<any>(null)
const popupRef = ref<any>(null)
const addressVisible = ref<boolean>(false)
const show = ref<any>({
  industryIndex: [0],
  industryStr: '',
  repairIndex: [0],
  repairStr: '',
  addressIndex: [0],
  addressStr: ''
})

const tagList = ref<any[]>([])
const readonly = ref<boolean>(false)

const formRef = ref<any>(null)

const form = ref<any>({
  community_id: community_id.value, //项目id
  building_id: '', //楼栋ID:0 是公共区域
  floor_id: '', //楼层ID
  address: '', //详细地址
  merchant_id: merchant_id.value, //租户ID
  merchant_name:userInfo.value.merchant_name,
  repair_user_id: userInfo.value.id, //报修人
  repair_type: '', //报修类型
  order_start_date: '', //预约上门开始时间
  order_end_date: '', //预约上门结束时间
  repair_tags: [], //故障描述
  description: "", //故障说明
  repair_imgs: [
    // "/repair_imgs/16546e81014a8decf58fab6b84d1ca0c.png"
  ] //故障视频/图片
})
const repairVisible = ref<boolean>(false)

// 报修类型
const repairTypes = ref<any[]>([])
const repairDates = ref<any>([])
// 报修地址选线
const repairAddress = ref<any[]>([])

// 上传
const fileList = ref<any>([])

const afterRead = async (event) => {
  console.log('jp=======event',event)
  uToastRef.value.show({
    type: 'loading',
    title: '正在加载',
    message: "正在加载",
    loading: true,
    duration: 1000*60*6,
    iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/loading.png'
  })

  // 测试一下上传 todo
  try{
    const file = event.file
    const sign: any = await upLoadFile(file, 'repair_imgs')
    const newUrl = await uniUpload(sign, file)
    const __fileList = [...fileList.value]
    __fileList.push({
      ...file,
      url: newUrl,
      subUrl: `/${sign.key}`
    })
    console.log('jp======__fileList',__fileList)
    fileList.value = __fileList
    setTimeout(() => {
      uToastRef.value.clearTimer()
    }, 600)
  }catch (e) {
    uToastRef.value.clearTimer()
    uToastRef.value.show({
      type: 'loading',
      message: "上传图片失败，请重试",
    })
  }
  // uni.uploadFile({
  //   url: sign.host,
  //   filePath: file.url,
  //   name: 'file',
  //   formData: sign,
  //   success: () => {
  //     console.log('jp======上传成功url', `${ASSETS_HOST}${sign.key}`)
  //     const __fileList = [...fileList.value]
  //     const __newUrl = `${ASSETS_HOST}${sign.key}`
  //     __fileList.push({
  //       ...file,
  //       url: __newUrl,
  //       subUrl: `/${sign.key}`
  //     })
  //     console.log('jp======__fileList',__fileList)
  //     fileList.value = __fileList
  //     setTimeout(() => {
  //       uToastRef.value.clearTimer()
  //     }, 600)
  //   },
  //   fail: () => {
  //     uToastRef.value.clearTimer()
  //     uToastRef.value.show({
  //       type: 'loading',
  //       message: "上传图片失败，请重试",
  //     })
  //   }
  // });
}
const deletePic = (event: any) => {
  fileList.value.splice(event.index, 1);
}
const sureFileType = (val) => {
  // 选择视频还是图片todo
  console.log('jp=======val',val)
}
// 设置选择报修地址后带出来的数据
const setAddressRelativeData = (item) => {
  form.value.repair_adress =  `${item.community_name}-${item.building_name}-${item.floor}`
  form.value.address = `${item.floor}${item.room_number}室`
  form.value.building_id = item.building_id
  form.value.floor_id = item.floor
  form.value.community_id = item.community_id

}
const selectRepairAddress = (val) => {
  const item = repairAddress.value[val]
  setAddressRelativeData(item)
}
const initData = () => {
  getAllRepairType({community_id: community_id.value}).then((res: any) => {
    console.log('jp======报修类型',res)
    repairTypes.value = res.data
  })
  getHouseList({merchant_id: merchant_id.value,page_num: 1, page_size: 300}).then((res: any) => {
    console.log('jp======房源列表',res)
    const item = res.data?.list[0]
    setAddressRelativeData(item)
    repairAddress.value = res.data.list
  })
  getRepairTime({}).then((res: any) => {
    console.log('jp======报修时间',res)
    repairDates.value = res.data
  })
}
initData()
const orderId = ref<any>('')
onLoad((option: any) => {
  // 判断 是编辑 还是新增
  form.value = {
    merchant_id: merchant_id.value, //租户ID
    merchant_name:userInfo.value.merchant_name,
    repair_user_id: userInfo.value.id, //报修人
  }
  console.log('jp=======option',option)
  const repairTypeData = option.repairType ? JSON.parse(option.repairType) : ''
  // repairTypeData  有值 证明是从 选择报修类型页面点进来的  否则就是直接创建报修工单
  orderId.value = ''
  if(repairTypeData) {
  //   新增
    tagList.value = repairTypeData.tags
    form.value.repair_type = repairTypeData.id
    form.value.repair_type_text = repairTypeData.name
  }
  if(option.opType === 'edit') {
  //   编辑  初始化 工单数据  todo
    orderId.value = option.id
    getOrderDetail({id: option.id}).then((res: any) =>{
      console.log('jp======工单详情',res)
      const {data} = res
      form.value = {
        repair_type_text: data.repair_type_text,
        repair_type: data.repair_type,
        community_name:  data.community_name,
        community_id:  data.community_id,
        building_id: data.building_id,
        building_name: data.building_name,
        floor_id: data.floor_id,
        room_number: data.address,
        merchant_name: data.merchant_name,
        merchant_id: data.merchant_id,
        real_name: data.create_user?.real_name,
        repair_user_id: data.create_user?.id,
        order_start_date: data.order_start_date,
        order_end_date: data.order_end_date,
        repair_tags: data.repair_tags,
        description: data.description,
        repair_imgs: data.repair_imgs,
        repair_adress: `${data.community_name}-${data.building_id}-${data.floor_id}`,
        address: data.address
      }
      repariDate.value.rTime = data.order_start_date  + '~' + moment(data.order_end_date).format('HH:mm')
      const index = repairTypes.value?.findIndex(item => item.id === data.repair_type)
      console.log('jp======index',index)
      tagList.value = index !== -1 ? repairTypes.value[index]?.tags: []
      console.log('jp======tagList.value',tagList.value)
      const sIndex = data.repair_tags ? tagList.value?.findIndex((item) => Number(data.repair_tags) === item.id) : -1
      if(sIndex !== -1) {
        tagList.value[sIndex].checked = true
      }
      const __fileList:any[] = []
      each(data.repair_imgs_arr, (item) => {
        __fileList.push({
          url: `${ASSETS_HOST}${item}`,
          subUrl: item
        })
      })
      fileList.value = __fileList
    })
  }

})
const selectRepair = (val) => {
  const item = repairTypes.value[val]
  console.log('jp=======item',item)
}
// 选择标签
const selectTag = (item: any, i: number) => {
  const __tagList = [...tagList.value]
  each(__tagList, (item, index) => {
    if(index === i) {
      item.checked = true
      return
    }
    item.checked = false
  })
  tagList.value = __tagList
}

// 选择报修时间
const selectServiceTime = () => {
  popupRef.value.open('bottom')
}
const closePopup = () => {
  popupRef.value.close()
}
const selectDate = (item: any, i: number) => {

  const __repairDates = [...repairDates.value]
  each(__repairDates, (cItem: any, index:number) => {
    cItem.isShowTime = index === i ? true : false
  })
  repairDates.values = __repairDates
}
const repariDate = ref<any>({})
// 选择时间
const selectTime = (i, childIndex) => {

  const __repairDates = [...repairDates.values]
  each(__repairDates[i].time_list, (subItem, index) => {
    if(index === childIndex) {
      subItem.isChecked = true
      repariDate.value = subItem
    } else {
      subItem.isChecked = false
    }

  })
  console.log('jp======__repairDates',__repairDates)
  repairDates.values = __repairDates
}

const handleSelect = () => {
  console.log('jp======repariDate.value',repariDate.value)
  repariDate.value.rTime = repariDate.value.start_date.substr(0, 10) + ' ' + repariDate.value.title
  form.value.order_start_date =  repariDate.value.start_date
  form.value.order_end_date =  repariDate.value.end_date
  popupRef.value.close()
}
// 提交报修
const confirm = async () => {
  const res= await formRef.value.validate()
  console.log('jp======res',res)
  if(!res.isPass) return
  // 修改参数
  const repair_tags: any[] = []
  const _storeTags: any[] = []
  each(tagList.value, (item: any) => {
    if(item.checked) {
      repair_tags.push(item.id)
      _storeTags.push(item.name)
    }
  })
  const repair_imgs: any[] = []
  each(fileList.value, (item) => {
    repair_imgs.push(item.subUrl)
  })
  const params = {
    ...res.data,
    id: merchant_id.value,
    repair_tags,
    repair_imgs
  }
  // 剩余报修提交缺少的字段  todo
  console.log('jp======form',form.value)
  console.log('jp======提交参数',params)
  let result: any
  if(orderId.value?.id) {
    result = await updateOrder(params)
  } else {
    result = await createOrder(params)
  }
  const {data, code, message} = result
  if( code === 200) {
    readonly.value = true
    uni.$showMsg('操作成功！')
    const pData = {
      ...form.value,
      storeTags: _storeTags?.length ? _storeTags.join(',') : '',
      real_name: userInfo.value.real_name,
      repair_time: repariDate.value.rTime,
      repair_id: data.repair_id
    }
    const orderData = JSON.stringify(pData)
    uni.navigateTo({
      url: `/subpkg/repair_complete_tip/index?orderData=${orderData}`
    })
  } else{
    uni.$showMsg(message)
  }
}
</script>

<style lang="scss" scoped>
.create_repair{
  //padding: 20px;
  .cus_item{

  }
  .form_title{
    font-size: $cus-font-size-16;
    padding-left: 8px;
    padding-top: 12px;
  }
  .my_info{
    .cus_item{
      justify-content: space-between;
    }
  }

  .tag_list{
    display: flex;
    padding-bottom: 4px;
    flex-wrap: wrap;
  }
  :deep(.item_block){
    display: block!important;
    .flex-row.flex-row-center-start{
      width: 100%!important;
    }
    & >.flex-1{
      width: 100%!important;
      padding-top: 8px;
    }
    textarea {
      min-height: 140px;
    }
  }
}
.date_section{
  display: flex;
  justify-content: space-between;
  position: relative;
  .time_week{
    color: $cus-color-1;
  }
  .time_date{
    font-size: $cus-font-size-14;
  }
  .date_item{
    padding: 2px 4px;
  }
  .date_item.selected{
    border-radius: 7px;
    background: $cus-color-8;
    .time_week{
      color: #fff;
    }
    .time_date{
      color: #fff;
    }
  }

  .time_section{
    display: flex;
    width: 100%;
    position: absolute;
    top: 50px;
    left: 0;
    flex-wrap: wrap;
    .select_time{
      width: 25%;
      box-sizing: border-box;

      //margin: 4px;

      .time_item{
        border: 1px solid #E5E5E5;
        border-radius: 4px;
        padding: 6px 8px;
        margin: 4px 6px;
        font-size: 12px;
      }
      .time_item.disabled{
        border-color: $cus-color-11;
        color: $cus-color-11;
      }
      .time_item.selected{
        border-color: $cus-color-8;
        color: #fff;
        background: $cus-color-8;
      }

    }
  }



}

.popup-content{
  padding-bottom: 140px;
}
</style>
<style lang="scss">
.create_repair{
  .u-upload{
    width: 100%;
    height: 100%;
    display: block!important;
    .u-upload__wrap{
      width: 100%;
      height: 100%;
      &>view{
        display: block;
        width: 100%;
        height: 100%;
      }
    }
  }
}


</style>